package com.newshub.business.controller;

import com.newshub.common.Result;
import com.newshub.business.dto.RegionQueryDTO;
import com.newshub.business.dto.PageResult;
import com.newshub.business.entity.Region;
import com.newshub.business.service.RegionService;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 区域管理控制器
 */
@RestController
@RequestMapping("/api/region")
@CrossOrigin(origins = "*")
public class RegionController {
    
    @Autowired
    private RegionService regionService;
    
    /**
     * 分页查询区域
     */
    @PostMapping("/page")
    @BusinessLog(level = LogLevel.INFO, description = "分页查询区域")
    public Result<PageResult<Region>> getRegionPage(@RequestBody RegionQueryDTO queryDTO) {
        try {
            PageResult<Region> result = regionService.getRegionPage(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询区域失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有区域
     */
    @GetMapping("/list")
    @BusinessLog(level = LogLevel.INFO, description = "获取所有区域")
    public Result<List<Region>> getAllRegions() {
        try {
            List<Region> regions = regionService.getAllRegions();
            return Result.success(regions);
        } catch (Exception e) {
            return Result.error("获取区域列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取区域
     */
    @GetMapping("/{id}")
    @BusinessLog(level = LogLevel.INFO, description = "根据ID获取区域")
    public Result<Region> getRegionById(@PathVariable Integer id) {
        try {
            Region region = regionService.getRegionById(id);
            if (region != null) {
                return Result.success(region);
            } else {
                return Result.error("区域不存在");
            }
        } catch (Exception e) {
            return Result.error("获取区域失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据名称获取区域
     */
    @GetMapping("/name/{name}")
    @BusinessLog(level = LogLevel.INFO, description = "根据名称获取区域")
    public Result<Region> getRegionByName(@PathVariable String name) {
        try {
            Region region = regionService.getRegionByName(name);
            if (region != null) {
                return Result.success(region);
            } else {
                return Result.error("区域不存在");
            }
        } catch (Exception e) {
            return Result.error("获取区域失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据代码获取区域
     */
    @GetMapping("/code/{code}")
    @BusinessLog(level = LogLevel.INFO, description = "根据代码获取区域")
    public Result<Region> getRegionByCode(@PathVariable String code) {
        try {
            Region region = regionService.getRegionByCode(code);
            if (region != null) {
                return Result.success(region);
            } else {
                return Result.error("区域不存在");
            }
        } catch (Exception e) {
            return Result.error("获取区域失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加区域
     */
    @PostMapping
    @BusinessLog(level = LogLevel.INFO, description = "添加区域")
    public Result<String> addRegion(@RequestBody Region region) {
        try {
            // 验证区域名称是否已存在
            Region existingRegion = regionService.getRegionByName(region.getName());
            if (existingRegion != null) {
                return Result.error("区域名称已存在");
            }
            
            // 验证区域代码是否已存在
            existingRegion = regionService.getRegionByCode(region.getCode());
            if (existingRegion != null) {
                return Result.error("区域代码已存在");
            }
            
            boolean success = regionService.addRegion(region);
            if (success) {
                return Result.success("添加区域成功");
            } else {
                return Result.error("添加区域失败");
            }
        } catch (Exception e) {
            return Result.error("添加区域失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新区域
     */
    @PutMapping("/{id}")
    @BusinessLog(level = LogLevel.INFO, description = "更新区域")
    public Result<String> updateRegion(@PathVariable Integer id, @RequestBody Region region) {
        try {
            region.setId(id);
            
            // 验证区域是否存在
            Region existingRegion = regionService.getRegionById(id);
            if (existingRegion == null) {
                return Result.error("区域不存在");
            }
            
            // 验证区域名称是否重复（排除自己）
            Region nameConflict = regionService.getRegionByName(region.getName());
            if (nameConflict != null && !nameConflict.getId().equals(id)) {
                return Result.error("区域名称已存在");
            }
            
            // 验证区域代码是否重复（排除自己）
            Region codeConflict = regionService.getRegionByCode(region.getCode());
            if (codeConflict != null && !codeConflict.getId().equals(id)) {
                return Result.error("区域代码已存在");
            }
            
            boolean success = regionService.updateRegion(region);
            if (success) {
                return Result.success("更新区域成功");
            } else {
                return Result.error("更新区域失败");
            }
        } catch (Exception e) {
            return Result.error("更新区域失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除区域
     */
    @DeleteMapping("/{id}")
    @BusinessLog(level = LogLevel.WARN, description = "删除区域")
    public Result<String> deleteRegion(@PathVariable Integer id) {
        try {
            // 验证区域是否存在
            Region region = regionService.getRegionById(id);
            if (region == null) {
                return Result.error("区域不存在");
            }
            
            boolean success = regionService.deleteRegion(id);
            if (success) {
                return Result.success("删除区域成功");
            } else {
                return Result.error("删除区域失败");
            }
        } catch (Exception e) {
            return Result.error("删除区域失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新区域状态
     */
    @PutMapping("/{id}/status")
    @BusinessLog(level = LogLevel.INFO, description = "更新区域状态")
    public Result<String> updateRegionStatus(@PathVariable Integer id, @RequestParam Integer status) {
        try {
            boolean success = regionService.updateRegionStatus(id, status);
            if (success) {
                return Result.success("更新区域状态成功");
            } else {
                return Result.error("更新区域状态失败");
            }
        } catch (Exception e) {
            return Result.error("更新区域状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量删除区域
     */
    @DeleteMapping("/batch")
    @BusinessLog(level = LogLevel.WARN, description = "批量删除区域")
    public Result<String> batchDeleteRegions(@RequestBody List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的区域");
            }
            
            boolean success = regionService.batchDeleteRegions(ids);
            if (success) {
                return Result.success("批量删除区域成功");
            } else {
                return Result.error("批量删除区域失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除区域失败: " + e.getMessage());
        }
    }
}
